/**
 * @author : 乔磊磊
 * @ide    : WebStorm
 * @date   : 2025/2/23 星期日 18:27
 * @desc   :
 */
import {sys} from "cc"
import {logger} from "../log";

export class StorageMgr {
    private _jsonData: { [key: string]: any } = {}
    private _markSave: boolean = false
    private _saveImmediate: boolean = false
    private _storageKey: string = 'game_'

    /**
     * hook 本地数据，用于sdk 本地数据的持久化
     */
    public hookLocalData(data: { [key: string]: any }) {
        this._jsonData = data
        this.save()
    }

    /**
     * 设置数据
     * 存储到本地
     * @param {string} key 关键字
     * @param {any}value  存储值
     * @returns
     */
    public setLocalData(key: string, value: any) {
        this._jsonData[key] = value
        if (this._saveImmediate) this.save();
        this._markSave = true
    }

    /**
     * 获取数据
     * 从本地读取
     * @param {string} key 关键字
     * @returns
     */
    public getLocalData(key: string) {
        return this._jsonData[key]
    }

    /**
     * 清除本地数据
     * 保存的游戏数据都会被清楚
     * 只在调试时使用
     */
    public clearUp() {
        this._jsonData = {}
        sys.localStorage.clear()
    }

    public init(gameName: string, saveImmediate: boolean = true) {
        this._storageKey += gameName
        this._saveImmediate = saveImmediate
        this.start()
    }

    private save() {
        let str = JSON.stringify(this._jsonData)
        // let zipStr = "@" + encryptString(str)
        let zipStr = "@" + str

        this._markSave = false
        sys.localStorage.setItem(this._storageKey, zipStr)
    }

    private start() {
        this._jsonData = {}

        let content = sys.localStorage.getItem(this._storageKey)
        if (content && content.length) {
            if (content.startsWith("@")) {
                content = content.substring(1)
                // content = decryptString(content)
            }

            try {
                //初始化操作
                this._jsonData = JSON.parse(content)
            } catch (err: any) {
                logger.error(err.message)
            }

        }

        //每隔5秒保存一次数据
        setInterval(() => {
            this.scheduleSave()
        }, 5000)
    }

    /**
     * 定时存储
     * @returns
     */
    private scheduleSave() {
        if (this._saveImmediate) return
        if (!this._markSave) {
            return
        }
        this.save()
    }
}

export const storageMgr = new StorageMgr()
